from socket import *
import os
import re
from Config import getConfig

MaxBytes = 1024 * 1024


class mySocket:

    def __init__(self, host, port):
        # ret = os.popen("netstat -nao | grep " + str("192.168.1.5:2234")).read()
        # print(ret)
        self.tcpSerSock = socket(AF_INET, SOCK_STREAM)
        try:
            self.tcpSerSock.bind((host, port))
            print("start socket "+str(host)+":"+str(port))
        except Exception as e:
            print(e)
            print("连接服务器失败,请检查服务器是否开启")
            print(host, ':', port)
            exit()
        self.tcpSerSock.listen(10)

    @staticmethod
    def socketSend(tcpSerSock: socket, data, com):
        arrBuf = bytearray(b'\xff\xaa\xff' + com.to_bytes(1, byteorder='little'))
        arrBuf += bytearray(len(data).to_bytes(4, byteorder='little'))
        arrBuf += bytearray(int(getConfig('client.config',
                                          'all', 'guid')).to_bytes(64, byteorder='little'))
        arrBuf += data
        tcpSerSock.sendall(arrBuf)
        return

    @staticmethod
    def socketReceive(tcpSerSock: socket):
        receiveData = tcpSerSock.recv(MaxBytes)
        # print(receiveData)
        comIndex = receiveData.find(b'\xff\xaa\xff')
        # print(comIndex)
        com = receiveData[comIndex + 3]
        dataSize = int.from_bytes(receiveData[comIndex + 4:comIndex + 8], 'little')
        guid = int.from_bytes(receiveData[comIndex + 8:comIndex + 72], 'little')
        data = receiveData[comIndex + 72:comIndex + 72 + dataSize]
        return com, dataSize, guid, data
